package com.power.leopard.remote;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import com.power.leopard.common.util.VersionUtils;

public class ServiceProviderFactory {

	private static Map<String, ProviderConfig<?>> serviceCache = new ConcurrentHashMap<String, ProviderConfig<?>>();
	
	public static <T> void publishService(ProviderConfig<T> providerConfig) {
		
	}

	public static <T> void addService(ProviderConfig<T> providerConfig) {
		String url = providerConfig.getUrl();
		String version = providerConfig.getVersion();

		if (StringUtils.isEmpty(version)) {
			serviceCache.put(url, providerConfig);
		} else {
			String serviceUrlWithVersion = getServiceUrlWithVersion(url, version);
			if (serviceCache.containsKey(url)) {
				serviceCache.put(serviceUrlWithVersion, providerConfig);
				ProviderConfig<?> defaultProviderConfig = serviceCache.get(url);
				String defaultVersion = defaultProviderConfig.getVersion();

				if (VersionUtils.compareVersion(defaultVersion, version) < 0) {
					// replace with the new version of service
					serviceCache.put(url, providerConfig);
				}
			} else {
				serviceCache.put(serviceUrlWithVersion, providerConfig);

				// use as the default config
				serviceCache.put(url, providerConfig);
			}
			ServiceMethodFactory.init(url);
		}
	}

	public static Map<String, ProviderConfig<?>> getAllServiceProviders() {
		return serviceCache;
	}

	public static String getServiceUrlWithVersion(String url, String version) {
		String newUrl = url;
		if (!StringUtils.isBlank(version)) {
			newUrl = url + "_" + version;
		}
		return newUrl;
	}
}
